package com.glela.order.service.impl;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.glela.api.model.AlipayAppKeyInfo;
import com.glela.api.model.PayAppKeyInfo;
import com.glela.api.pay.alipay.component.Alipay;
import com.glela.api.pay.util.AlipayConfig;
import com.glela.api.pay.util.PayConfig;
import com.glela.api.pay.wechat.component.WeChat;
import com.glela.api.pay.wechat.component.impl.WeChat0Impl;
import com.glela.api.pay.wechat.component.impl.WeChatImpl;
import com.glela.biz.RedPacketBiz;
import com.glela.common.constant.BaseConstants;
import com.glela.common.constant.KeepAccountsTypeConstants;
import com.glela.common.constant.OrderStatusEnum;
import com.glela.common.constant.PayTypeEnum;
import com.glela.common.constant.StoreTypeEnum;
import com.glela.common.model.sms.SMSAfterSaleApply;
import com.glela.common.service.SMSService;
import com.glela.common.util.Base64Util;
import com.glela.common.util.Config;
import com.glela.common.util.DateUtil;
import com.glela.common.util.DateUtils;
import com.glela.common.util.HttpUtil;
import com.glela.common.util.MD5Utils;
import com.glela.common.util.OrderUtil;
import com.glela.domain.dto.BackRedPacketRequest;
import com.glela.goods.mapper.GoodsCommentMapper;
import com.glela.goods.mapper.GoodsExtendedAttributeMapper;
import com.glela.goods.mapper.ProductMapper;
import com.glela.goods.model.GoodsExtends;
import com.glela.goods.model.Product;
import com.glela.order.mapper.AfterSalesMapper;
import com.glela.order.mapper.CommisionMapper;
import com.glela.order.mapper.OrderDetailMapper;
import com.glela.order.mapper.OrderInfoMapper;
import com.glela.order.mapper.OrderObjectMapper;
import com.glela.order.mapper.OrderPayMapper;
import com.glela.order.mapper.OrderSettlementMapper;
import com.glela.order.mapper.RefundReasonMapper;
import com.glela.order.mapper.StoreRefundAddressMapper;
import com.glela.order.mapper.XZAfterSalesLogMapper;
import com.glela.order.model.AfterSales;
import com.glela.order.model.Commision;
import com.glela.order.model.OrderDetail;
import com.glela.order.model.OrderInfo;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderPay;
import com.glela.order.model.OrderSettlement;
import com.glela.order.model.RefundReason;
import com.glela.order.model.StoreRefundAddress;
import com.glela.order.model.XZAfterSalesLog;
import com.glela.order.model.request.RequestAfterSalesModel;
import com.glela.order.model.response.ResponseAfterSalesListModel;
import com.glela.order.model.response.ResponseAfterSalesModel;
import com.glela.order.model.response.ResponseAfterSalesSuccess;
import com.glela.order.model.response.ResponseReason;
import com.glela.order.model.response.ResponseStoreRefundAddress;
import com.glela.order.service.AfterSalesService;
import com.glela.order.service.CommissionService;
import com.glela.order.service.OrderService;
import com.glela.order.service.OrderStatusService;
import com.glela.order.vo.ParamsCommisionVo;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.AppSecretMapper;
import com.glela.platform.mapper.CUserMoneyChangeMapper;
import com.glela.platform.mapper.CUserPointTransactionMapper;
import com.glela.platform.mapper.OperationLogMapper;
import com.glela.platform.mapper.UserBankMapper;
import com.glela.platform.mapper.UserInfoMapper;
import com.glela.platform.mapper.UserJournalMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.mapper.UserMoneyMapper;
import com.glela.platform.mapper.UserPointJournalMapper;
import com.glela.platform.model.AppSecret;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.CUserMoneyChange;
import com.glela.platform.model.CUserPointTransaction;
import com.glela.platform.model.MoneyBusinessType;
import com.glela.platform.model.OperationLog;
import com.glela.platform.model.PushMessage;
import com.glela.platform.model.User;
import com.glela.platform.model.UserInfo;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserMoney;
import com.glela.platform.model.UserPointJournal;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.CUserPointTransactionService;
import com.glela.platform.service.MoneyBusinessTypeService;
import com.glela.platform.service.PushMessageService;
import com.glela.platform.service.UserMoneyService;
import com.glela.platform.vo.ParamsUserXzbTransactionVo;
import com.glela.statistics.service.UserEarningsService;
import com.glela.talent.util.MyDateUtil;

/**
 * 售后
 * @author MaoZeYao
 *	
 */
@Service("afterSalesService")
public class AfterSalesServiceImpl implements AfterSalesService {
	private static Logger logger = LoggerFactory.getLogger(AfterSalesServiceImpl.class);
	private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	

	@Autowired
	private List<WeChat> weChatList;
	@Autowired
	private SMSService					smsService;
	@Autowired
	private Alipay					alipay;
	@Autowired
	private UserPointJournalMapper userPointJournalMapper;
	@Autowired
	private OrderPayMapper orderPayMapper;
	@Autowired
	private CUserMoneyChangeMapper moneyChangeMapper;
	@Autowired
	private CUserPointTransactionMapper pointTransactionMapper;
	@Autowired
	private UserMoneyMapper userMoneyMapper;
	@Autowired
	private UserJournalMapper userJournalMapper;
	@Autowired
	private AfterSalesMapper afterSalesMapper;
	
	@Autowired
	private MoneyBusinessTypeService moneyBusinessTypeService;
	
	@Resource(name = "orderService2")
	private OrderService orderService2;
	
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	
	@Autowired
	private RefundReasonMapper refundReasonMapper;
	
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	
	@Autowired
	private StoreRefundAddressMapper storeRefundAddressMapper;
	
	@Autowired
	private ProductMapper productMapper;
	
	@Autowired
	private OrderObjectMapper orderObjectMapper;
	
	@Autowired
	private OrderSettlementMapper orderSettlementMapper;
	
	@Autowired
	private CommisionMapper commisionMapper;
	
	@Autowired
	private PushMessageService pushMessageService;
	@Autowired
	private UserEarningsService userEarningsService;
	
	@Autowired
	private GoodsCommentMapper goodsCommentMapper;
	
	@Autowired
	private XZAfterSalesLogMapper xZAfterSalesLogMapper;
	
	@Autowired
	private AppSecretMapper appSecretMapper;
	
	@Autowired
	private OrderStatusService orderStatusService;
	
	@Autowired
	private UserMoneyService userMoneyService;
	
	@Autowired
	private UserInfoMapper userInfoMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private OperationLogMapper operationLogMapper;
	
	@Autowired
	private BaseRestrictionsService  baseRestrictionsService;
	
	@Autowired
	private CommissionService  commissionService;
	
	@Autowired
	private CUserPointTransactionMapper  cUserPointTransactionMapper;
	
	@Autowired
	private CUserPointTransactionService  cUserPointTransactionService;
	@Autowired
	private RedPacketBiz redPacketBiz;
	@Autowired
	private GoodsExtendedAttributeMapper goodsExtendedAttributeMapper;

	@Autowired
	private UserBankMapper userBankMapper;
	public static String stringMD5(String pw) {
		try {
			// 拿到一个MD5转换器（如果想要SHA1参数换成”SHA1”）
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			// 输入的字符串转换成字节数组
			byte[] inputByteArray = pw.getBytes();
			// inputByteArray是输入字符串转换得到的字节数组
			messageDigest.update(inputByteArray);
			// 转换并返回结果，也是字节数组，包含16个元素
			byte[] resultByteArray = messageDigest.digest();
			// 字符数组转换成字符串返回
			return byteArrayToHex(resultByteArray);
		} catch (NoSuchAlgorithmException e) {
			return null;
		}
	}
	
	public static String byteArrayToHex(byte[] byteArray) {
		// 首先初始化一个字符数组，用来存放每个16进制字符
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
		// new一个字符数组，这个就是用来组成结果字符串的（解释一下：一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方））
		char[] resultCharArray = new char[byteArray.length * 2];
		// 遍历字节数组，通过位运算（位运算效率高），转换成字符放到字符数组中去
		int index = 0;
		for (byte b : byteArray) {
			resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];
			resultCharArray[index++] = hexDigits[b & 0xf];
		}
		// 字符数组组合成字符串返回
		return new String(resultCharArray);
	}
	
	/**
	 * 请求发送
	 * @param method
	 * @param dataJson
	 * @return
	 * @throws IOException 
	 */
	protected String sendPost(String method, String dataJson) throws IOException {
		String requestResult = "";
		String data = Base64Util.encode(dataJson);
		String sign = MD5Utils.encryptNoStart(data + Config.getString("xz.secret"));
		StringBuffer sb = new StringBuffer();
		sb.append("{\r\n");
		sb.append("\"method\":\"" + method + "\",\r\n");
		sb.append("\"timestamp\":\"" + DateUtil.toString(new Date()) + "\",\r\n");
		sb.append("\"app_key\":\"" + Config.getString("xz.appKey") + "\",\r\n");
		sb.append("\"sign\":\"" + sign + "\",\r\n");
		sb.append("\"data\":\"" + data + "\"\r\n}");
		if (logger.isDebugEnabled()) {
			logger.debug("oms售后接口[{}]明文：{} 密文：{}", method, dataJson, sb);
		}
		requestResult = HttpUtil.doPost(sb.toString(), Config.getString("xz.sendOrder"), "application/json");
		return requestResult;
	}
	
	/**
	 * 瞬时订单查询冻结订单
	 * @param orderInfoSn
	 * @return
	 */
	protected void orderStatusInWMS(String orderInfoSn, int applyType, String afterSn, String pproductSn){
		XZAfterSalesLog logModel = new XZAfterSalesLog();
		try {
			String method = "aftersale.checkOrderStatus";
			String dataJson = "{\"order_sn\":\""+ orderInfoSn +"\",\"apply_type\":\""+applyType+"\",\"pproduct_sn\":\""+pproductSn+"\"}";
			String result = sendPost(method, dataJson);
			JSONObject jsonObject = JSONObject.parseObject(result);
			
			if("00000".equals(jsonObject.get("code").toString())){
				logModel.setOrderInfoSn(orderInfoSn);
				logModel.setAfterSn(afterSn);
				logModel.setResult(jsonObject.get("msg").toString());
				logModel.setReturnCode(jsonObject.get("code").toString());
				logModel.setSteps(1);
				logModel.setRemark(jsonObject.get("msg").toString());
			} else {
				logModel.setOrderInfoSn(orderInfoSn);
				logModel.setResult(result);
				logModel.setAfterSn(afterSn);
				logModel.setResult(jsonObject.get("msg").toString());
				logModel.setReturnCode(jsonObject.get("code").toString());
				logModel.setSteps(1);
				logModel.setRemark(jsonObject.get("msg").toString());
				if(jsonObject.get("msg")!=null&&jsonObject.get("msg").toString().contains("已发货")){//订单已发货不退运费 强制修改为退货退款
					afterSalesMapper.updateAfterSalesRefundTypeByCustomerServiceNumber(afterSn,2);
				}
			}
			xZAfterSalesLogMapper.insertIntoLogs(logModel);
		} catch (Exception e) {
			// TODO: handle exception
			logModel.setOrderInfoSn(orderInfoSn);
			logModel.setResult("");
			logModel.setAfterSn(afterSn);
			logModel.setRemark("系统异常");
			logModel.setSteps(1);
			logModel.setStatus(0);
			xZAfterSalesLogMapper.insertIntoLogs(logModel);
		}
	}
	
	/**
	 * 取消仅退款的订单
	 * @param isRefund
	 * @param productBn
	 * @param orderInfoSn
	 * @param afterSn
	 * @param orderDetail
	 * @param code
	 * @param freigth_amount
	 */
	protected void freezeOrder(String productBn,String orderInfoSn,String afterSn,OrderDetail orderDetail, int code,Integer freigth_amount) {
		XZAfterSalesLog logModel = new XZAfterSalesLog();
		String result = "";
		try {
			String method = "aftersale.unfreezeOrCancelOrder";
			DecimalFormat df = new DecimalFormat("######0.00");
			double realMoney = Double.parseDouble(df.format((orderDetail.getTotalFee().doubleValue()) / 100));
			double totalMoney = Double.parseDouble(df.format((orderDetail.getTotalFee().doubleValue() + orderDetail.getCashCoin().doubleValue()+orderDetail.getBalancePaid().doubleValue()) / 100));
			double cashMoney = Double.parseDouble(df.format((orderDetail.getCashCoin().doubleValue()) / 100));
			double balanceMoney = Double.parseDouble(df.format((orderDetail.getBalancePaid().doubleValue()) / 100));
			double discountAmount = Double.parseDouble(df.format((orderDetail.getPromotionDiscount().doubleValue()) / 100+(orderDetail.getoActivDiscountFee().doubleValue()) / 100));
			double ActivDiscountAmount = Double.parseDouble(df.format((orderDetail.getoActivDiscountFee().doubleValue()) / 100));
			double freigthAmount = Double.parseDouble(df.format((freigth_amount.doubleValue()) / 100));
			String dealData = "{\"product_info\":[{\"product_sn\":\"" + productBn +"\",\"activity_discount_amount\":\""+ ActivDiscountAmount+ "\",\"paid_amount\":"+ totalMoney +",\"paid_amount_cash\":"+ realMoney + ",\"paid_amount_coin\":"+ cashMoney +",\"freigth_amount\":"+freigthAmount+",\"paid_amount_balance\":"+ balanceMoney + ",\"discount_amount\":"+ discountAmount + "}],\"order_sn\":\""+ orderInfoSn +"\",\"code\":"+ code +"}";
			result = sendPost(method, JSONObject.toJSONString(dealData));
			JSONObject jsonObject = JSONObject.parseObject(result);
			if("00000".equals(jsonObject.get("code").toString())){
				logModel.setOrderInfoSn(orderInfoSn);
				logModel.setResult(result);
				logModel.setAfterSn(afterSn);
				logModel.setResult(jsonObject.get("msg").toString());
				logModel.setReturnCode(jsonObject.get("code").toString());
				logModel.setSteps(2);
				
			} else {
				logModel.setOrderInfoSn(orderInfoSn);
				logModel.setResult(result);
				logModel.setAfterSn(afterSn);
				logModel.setResult(jsonObject.get("msg").toString());
				logModel.setReturnCode(jsonObject.get("code").toString());
				logModel.setSteps(2);
				logModel.setStatus(0);
			}
			xZAfterSalesLogMapper.insertIntoLogs(logModel);
		} catch (Exception e) {
			// TODO: handle exception
			logModel.setOrderInfoSn(orderInfoSn);
			logModel.setResult("");
			logModel.setAfterSn(afterSn);
			logModel.setRemark("系统异常");
			logModel.setSteps(2);
			logModel.setStatus(0);
			xZAfterSalesLogMapper.insertIntoLogs(logModel);
		}
	}
	
	/**
	 * 解冻订单
	 * @param orderInfoSn
	 * @param afterSn
	 */
	/*protected void unfreezeOrder(String orderInfoSn,String afterSn,OrderDetail orderDetail) {
		XZAfterSalesLog logModel = new XZAfterSalesLog();
		try {
			String result = "";
			String method = "aftersale.unfreezeOrCancelOrder";
			DecimalFormat df = new DecimalFormat("######0.00");
			double realMoney = Double.parseDouble(df.format((orderDetail.getTotalFee().doubleValue()) / 100));
			double totalMoney = Double.parseDouble(df.format((orderDetail.getTotalFee().doubleValue() + orderDetail.getCashCoin().doubleValue()) / 100));
			double cashMoney = Double.parseDouble(df.format((orderDetail.getCashCoin().doubleValue()) / 100));
			double discountAmount = Double.parseDouble(df.format((orderDetail.getPromotionDiscount().doubleValue()) / 100));
			
			String dealData = "{\"product_info\":[{\"product_sn\":\"" + productBn + "\",\"paid_amount\":"+ realMoney +",\"paid_amount_cash\":"+ totalMoney + ",\"paid_amount_coin\":"+ cashMoney + ",\"discount_amount\":"+ discountAmount + "}],\"order_sn\":\""+ orderInfoSn +"\",\"code\":"+ code +"}";
			// String dealData = "{\"order_sn\":\""+ orderInfoSn +"\",\"code\":1}";
			logger.info("----->解冻订单业务参数" + dealData);
			result = sendPost(method, JSONObject.toJSONString(dealData));
			JSONObject jsonObject = JSONObject.parseObject(result);
			if("00000".equals(jsonObject.get("code").toString())){
				logModel.setOrderInfoSn(orderInfoSn);
				logModel.setResult(result);
				logModel.setAfterSn(afterSn);
				logModel.setSteps(3);
				logModel.setResult(jsonObject.get("msg").toString());
				logModel.setReturnCode(jsonObject.get("code").toString());
			} else {
				logModel.setOrderInfoSn(orderInfoSn);
				logModel.setResult(result);
				logModel.setAfterSn(afterSn);
				logModel.setSteps(3);
				logModel.setStatus(0);
				logModel.setResult(jsonObject.get("msg").toString());
				logModel.setReturnCode(jsonObject.get("code").toString());
			}
			xZAfterSalesLogMapper.insertIntoLogs(logModel);
		} catch (Exception e) {
			// TODO: handle exception
			logModel.setOrderInfoSn(orderInfoSn);
			logModel.setResult("");
			logModel.setAfterSn(afterSn);
			logModel.setRemark("系统异常");
			logModel.setSteps(3);
			logModel.setStatus(0);
			xZAfterSalesLogMapper.insertIntoLogs(logModel);
		}
	}*/
	
	/**
	 * 回寄通知（退货通知单接口）
	 * @param productNums
	 * @param productBn
	 * @param orderInfoSn
	 * @param afterSn
	 * @param expressCode
	 * @param expressNo
	 */
	protected void addReturnOrder(int productNums,String productBn,String orderInfoSn,String afterSn,String expressCode,String expressNo) {
		XZAfterSalesLog logModel = new XZAfterSalesLog();
		String result = "";
		try {
			String method = "aftersale.addReturnOrder";
			String dealData = "{\"product_info\":[{product_sn:\"" + productBn + "\",\"product_nums\":"+ productNums +",\"is_gift\":"+ false + "}],\"order_sn\":\""+ orderInfoSn +"\",\"express_code\":\""+ expressCode +"\",\"express_no\":\""+ expressNo +"\"}";
			logger.info("----->回寄通知参数" + dealData);
			result = sendPost(method, JSONObject.toJSONString(dealData));
			// result = "{\"data\":\"170228134\",\"code\":\"00000\",\"msg\":\"退货通知单创建成功！\"}";
			JSONObject jsonObject = JSONObject.parseObject(result);
			if("00000".equals(jsonObject.get("code").toString())){
				String returnSn = jsonObject.get("data").toString();
				afterSalesMapper.updateAfterSalesReturnOrderId(afterSn,returnSn);
				logModel.setOrderInfoSn(orderInfoSn);
				logModel.setResult(result);
				logModel.setAfterSn(afterSn);
				logModel.setSteps(4);
				logModel.setResult(jsonObject.get("msg").toString());
				logModel.setReturnCode(jsonObject.get("code").toString());
				xZAfterSalesLogMapper.insertIntoLogs(logModel);
			} else {
				logModel.setOrderInfoSn(orderInfoSn);
				logModel.setResult(result);
				logModel.setAfterSn(afterSn);
				logModel.setSteps(4);
				logModel.setResult(jsonObject.get("msg").toString());
				logModel.setReturnCode(jsonObject.get("code").toString());
				xZAfterSalesLogMapper.insertIntoLogs(logModel);
			}
		} catch (Exception e) {
			// TODO: handle exception
			logModel.setOrderInfoSn(orderInfoSn);
			logModel.setResult("");
			logModel.setAfterSn(afterSn);
			logModel.setSteps(4);
			logModel.setRemark("系统异常");
			logModel.setStatus(0);
			xZAfterSalesLogMapper.insertIntoLogs(logModel);
			e.printStackTrace();
		}
	}
	
	/**
	 * 退款单推送接口addRefundOrder
	 * @param isRefund
	 * @param productBn
	 * @param orderInfoSn
	 * @param afterSn
	 * @param orderDetail
	 */
	protected void addRefundOrder(String productBn,String orderInfoSn,String afterSn,OrderDetail orderDetail,String returnSn,String afterTime) {
		XZAfterSalesLog logModel = new XZAfterSalesLog();
		String result = "";
		try {
			String method = "aftersale.addRefundOrder";
			DecimalFormat df = new DecimalFormat("######0.00");
			double realMoney = Double.parseDouble(df.format((orderDetail.getTotalFee().doubleValue()) / 100));
			double totalMoney = Double.parseDouble(df.format((orderDetail.getTotalFee().doubleValue() + orderDetail.getCashCoin().doubleValue()+orderDetail.getBalancePaid().doubleValue()) / 100));
			double cashMoney = Double.parseDouble(df.format((orderDetail.getCashCoin().doubleValue()) / 100));
			double balanceMoney = Double.parseDouble(df.format((orderDetail.getBalancePaid().doubleValue()) / 100));
			double returnPrice = Double.parseDouble(df.format((orderDetail.getSalePrice().doubleValue())/100));
			
			String dealData = "{\"return_order_id\":\""+ returnSn +"\",\"refund_amount\":"+ totalMoney +",\"refund_time\":\""+ afterTime + "\",\"product_info\":[{\"product_sn\":\""+productBn+"\",\"product_nums\":"+orderDetail.getQuantity()+",\"return_price\":"+ returnPrice +",\"return_amount_cash\":"+ realMoney +",\"paid_amount_balance\":"+ balanceMoney+",\"return_amount_coin\":"+ cashMoney +"}]}";
			logger.info("----->退单推送业务参数：" + dealData);
			result = sendPost(method, JSONObject.toJSONString(dealData));
			JSONObject jsonObject = JSONObject.parseObject(result);
			if("00000".equals(jsonObject.get("code").toString())){
				logModel.setOrderInfoSn(orderInfoSn);
				logModel.setResult(result);
				logModel.setAfterSn(afterSn);
				logModel.setSteps(5);
				logModel.setResult(jsonObject.get("msg").toString());
				logModel.setReturnCode(jsonObject.get("code").toString());
			} else {
				logModel.setOrderInfoSn(orderInfoSn);
				logModel.setResult(result);
				logModel.setAfterSn(afterSn);
				logModel.setSteps(5);
				logModel.setStatus(0);
				logModel.setResult(jsonObject.get("msg").toString());
				logModel.setReturnCode(jsonObject.get("code").toString());
			}
			xZAfterSalesLogMapper.insertIntoLogs(logModel);
		} catch (Exception e) {
			// TODO: handle exception
			logModel.setOrderInfoSn(orderInfoSn);
			logModel.setResult("");
			logModel.setAfterSn(afterSn);
			logModel.setSteps(5);
			logModel.setRemark("系统异常");
			logModel.setStatus(0);
			xZAfterSalesLogMapper.insertIntoLogs(logModel);
		}
	}
	
	/**
	 * 发起售后
	 * @throws ParseException 
	 */
	@Override
	public ResponseEntity<?> launchAfterSalesApplication(RequestAfterSalesModel model) throws ParseException {
		// TODO Auto-generated method stub
		ResponseAfterSalesModel resModel = new ResponseAfterSalesModel();
		//获取订单详情
		OrderDetail orderDetail = orderDetailMapper.selectByPrimaryKey(model.getOrderDetailId());
		OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderDetail.getOrderId());
		OrderObject orderObject = orderObjectMapper.selectByPrimaryKey(orderDetail.getOrderObjectId());
		BaseRestrictions baseRestrictions=
			baseRestrictionsService.getBaseRestrictionsForCache("open_store_limit_after_sale");
		//限制开店单不允许售后
		if(orderObject.getOpenStore()==1&&orderDetail.getIsOpenStoreGoods()==1&&baseRestrictions!=null&&
				DateUtils.compare_date_HHmmss(DateUtil.getNow(),baseRestrictions.getName())>0){
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C80001), HttpStatus.OK);
		}
		//限制海外购产品不允许售后
		GoodsExtends goodsExtends=goodsExtendedAttributeMapper.selectExtendsAttrByGoodsID(orderDetail.getGoodId());
		if(goodsExtends!=null&&goodsExtends.getOverseasGoods()==1) {//是海外购产品
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20428), HttpStatus.OK);
		}
		if(!(orderInfo.getUserId()).equals(model.getUserId())){
			// 当前订单不属于这个用户
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
		}
		if (orderDetail.getStatus() == 0 ||
		    orderDetail.getStatus() == 1 ||
		    orderDetail.getStatus() == 5 ||
		    orderDetail.getStatus() == 6 ||
		    orderDetail.getStatus() == 7 ) {
			// 此订单不符合售后规则
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
		}
		if(orderDetail.getStatus() == 4){
			MyDateUtil util = MyDateUtil.INSTANCE;
			if(DateUtil.betweenTime(orderDetail.getUpdateTime(), util.getAccurateDays(orderDetail.getUpdateTime(), 7)) == 0){
				// 已经超过售后时间了
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C80002), HttpStatus.OK);
			}
		}
		//获取退款理由
		List<RefundReason> reasons = refundReasonMapper.selectRefundReasonByType(orderDetail.getStatus());
		List<ResponseReason> resReason = new ArrayList<ResponseReason>();
		for(RefundReason reason : reasons){
			ResponseReason resRea = new ResponseReason();
			resRea.setReason(reason.getReason());
			resRea.setType(reason.getType());
			resReason.add(resRea);
		}
		resModel.setRefundReason(resReason);//放入退款原因
		resModel.setGoodId(orderDetail.getGoodId());//放入商品ID
		resModel.setGoodsName(orderDetail.getGoodName());//放入商品名称
		resModel.setGoodImg(orderDetail.getNavigateImg1());//放入商品导航图
		resModel.setGoodSpecInfo(orderDetail.getSpecName());//放入商品规格信息
		resModel.setOrderSn(afterSalesMapper.selectOrderInfoSnByOrderInfoId(orderDetail.getOrderId()));//放入子订单的单号
		resModel.setRefundCashMoney(orderDetail.getCashCoin());//实际使用的现金币
		resModel.setRefundBalancePaid(orderDetail.getBalancePaid());//实际使用的余额 
		resModel.setRefundMoney(orderDetail.getTotalFee());//实际支付的现金
		resModel.setStatus(orderDetail.getStatus());
		resModel.setQuantity(orderDetail.getQuantity());// 放入商品数量
		if(orderDetail.getStatus() == 2){
			resModel.setIsRefund(1);
		}
		if(orderDetail.getStatus() == 3 || orderDetail.getStatus() == 4){
			resModel.setIsRefund(2);
		}
		return new ResponseEntity<>(new ResponseResultModel<ResponseAfterSalesModel>(resModel), HttpStatus.OK);
	}

	/**
	 * 保存售后申请
	 * update by gaoweiqi 2018-8-20
	 * @throws Exception 
	 */
	@Override
	public ResponseEntity<?> saveAfterSalesApplication(RequestAfterSalesModel model) throws Exception {
		// TODO Auto-generated method stub
		//获取订单详情
		OrderDetail orderDetail =  orderDetailMapper.selectByPrimaryKey(model.getOrderDetailId());
		AfterSales afterSale = afterSalesMapper.selectAfterSalesByOrderDetailId(model.getOrderDetailId());
		if(afterSale != null){
			// 请不要重复申请售后
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C80003), HttpStatus.OK);
		}
		Product product = productMapper.selectProductByIdNoStatus(orderDetail.getProductId());
		OrderInfo orderInfo = orderInfoMapper.selectOrderInfoEntityById(orderDetail.getOrderId());
		// 生成售后服务单号
		String afterSn = "A" + OrderUtil.getOrderSn();
		AfterSales saveModel = new AfterSales();
		saveModel.setCustomerServiceNumber(afterSn);
		saveModel.setUserId(orderDetail.getUserId());
		saveModel.setOrderObjectId(orderDetail.getOrderObjectId());
		saveModel.setOrderInfoId(orderDetail.getOrderId());
		saveModel.setOrderDetailId(orderDetail.getId());
//		saveModel.setIsRefund(model.getIsRefund());
		saveModel.setIsRefund(1);//直接给默认值 默认是1 
		saveModel.setRefundCashMoney(orderDetail.getCashCoin());//妆币
		saveModel.setRefundBalancePaid(orderDetail.getBalancePaid());//余额付
		saveModel.setStoreId(orderDetail.getStoreId().longValue());
		saveModel.setRefundMoney(orderDetail.getTotalFee().longValue());//现金
		saveModel.setUserFirstReason(model.getUserFirstReason());
		saveModel.setUserRefundReason(model.getUserRefundReason());
		saveModel.setType(model.getType());
		saveModel.setImgProof1(model.getImgProof1());
		saveModel.setImgProof2(model.getImgProof2());
		saveModel.setImgProof3(model.getImgProof3());
		saveModel.setOrderInfoSn(orderInfo.getOrderSn());
		saveModel.setQuantity(orderDetail.getQuantity());
		saveModel.setProductBn(product.getProductBn());
		saveModel.setProductId(product.getId());
		saveModel.setStatus(1);
		saveModel.setReturnOrderId("");
		saveThis(saveModel, false);
		 //提交售后申请发送短信
				//订单号   店主PersionId
				String recommendFrom = orderDetail.getRecommendFrom();
				String orderSn = orderInfo.getOrderSn();
				//System.out.println("推荐人" +recommendFrom +"orderSn" + orderSn+"orderDeatilId"+model.getOrderDetailId());
				//店主 不为空 不是校妆姐姐  发送短信
		if (null != recommendFrom && !BaseConstants.XZ_SISTER_PERSION_ID.equals(recommendFrom)) {
					//查询店主电话 
					UserInfo userInfo = userInfoMapper.selectUserInfoByPersionId(recommendFrom);
					if(userInfo != null){
				//						String smsUrl = baseRestrictionsService.getBaseRestrictionsForCache("sendSms_url").getName();
				//						String account = baseRestrictionsService.getBaseRestrictionsForCache("sendSms_account").getName();
				//						String pwd = baseRestrictionsService.getBaseRestrictionsForCache("sendSms_pwd").getName();
						Long userStoreId = userInfo.getUserId();
						User userStore = userMapper.selectByPrimaryKey(userStoreId);
						String date = DateUtils.dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
					//购买用户的昵称
					User userCustoer = userMapper.selectByPrimaryKey(orderDetail.getUserId());
					
				//					String msg = URLEncoder.encode("您的会员（"+userCustoer.getNickName()+ "）申请售后服务，订单号："+orderSn+"，申请时间："+date+"。【校妆网】", "UTF-8");
				//				SmsContents contents = new SmsContents(account, pwd, userStore.getUserName(), msg);
				//				String code = HttpUtil.doPost(contents.toString(), smsUrl, "application/x-www-form-urlencoded");
				//				String resultInfo = SmsContentsError.checkCode(code);

				SMSAfterSaleApply smsTemplate = new SMSAfterSaleApply(userStore.getUserName());
				smsTemplate.setMemberNickname(userCustoer.getNickName());
				smsTemplate.setOrderSn(orderSn);
				smsTemplate.setCreateTime(date);
				Object resultInfo = smsService.afterSaleApply(smsTemplate);

					OperationLog log = new OperationLog();
					log.setObjId(userStoreId.intValue());
					log.setObjName(String.valueOf(userStoreId));
					log.setModule("afterSale");
					log.setOperateType("sendSms");
					Long createLongTime = ((new Date().getTime()) / 1000);
					log.setCreatedAt(createLongTime.intValue());
					log.setDescription("申请售后发送短信给店主，店主电话"+userStore.getUserName()+"订单号:"+orderSn+"。返回信息:"+resultInfo);
					operationLogMapper.insert(log);
					
					}
				}
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	/**
	 * 售后保存接口
	 * @author gaoweiqi
	 * @date 2017年8月19日 12:44:05
	 * @param orderDetail
	 */
	protected void saveThis (AfterSales saveModel,boolean auto) {
		int insertStatus = afterSalesMapper.insertIntoAfterSales(saveModel);
		if(insertStatus <= 0){
			logger.info("---->售后保存违反uinque约束：" + saveModel.getOrderInfoSn());
		}
		AfterSales afterSales=
			afterSalesMapper.selectAfterSalesByCustomerServiceNumber(
					saveModel.getCustomerServiceNumber());//售后单号
		if(afterSales==null){
			logger.info("---->售后保存失败：" + saveModel.getOrderInfoSn());
		}
		// 分佣开关关闭 修改订单的状态为售后中
		int updateStatus  = orderDetailMapper.updateOrderDetailToRefund(saveModel.getOrderObjectId(),
				saveModel.getOrderInfoId(), saveModel.getOrderDetailId());
		if(updateStatus <= 0){
			logger.info("----->关闭分佣开关失败" + saveModel.getOrderInfoSn());
		}
		 
		//根据余额和妆币支付 生成事务信息 

		//余额付不为空 生成事务插入到余额事务表中
		if(saveModel.getRefundBalancePaid()>0){
			//判断售后类型
			MoneyBusinessType moneyBusinessType=moneyBusinessTypeService.selectMoneyBusinessByTypeId(7);//退货返还
			Commision c=new Commision();
			c.setOrderDetailId(saveModel.getOrderDetailId());//明细ID
			c.setOrderInfoId(saveModel.getOrderInfoId());//行ID
			c.setOrderObjectId(saveModel.getOrderObjectId());//头ID
			c.setUserId(saveModel.getUserId());//用户ID
			c.setType(0);//类型 
			c.setFee(saveModel.getRefundBalancePaid());//余额付
			c.setSourceId(afterSales.getId());//源ID
			c.setIsCustom(0);//是否手工
			c.setStatus(0);
			c.setComment("申请售后  返还余额付"); //备注
			c.setBusinessTypeId(7);//类型id
			c.setBusinessTypeName(moneyBusinessType==null?"":moneyBusinessType.getTypeName());//类型名字
			int count=commisionMapper.insertSelective(c);
			if(count<=0){
				logger.error("----->添加余额事务失败,子订单号:"+saveModel.getOrderDetailId());
			}
		}
		//妆币付不为空 生成事务插入到妆币事务表中
		if(saveModel.getRefundCashMoney()>0){
			//判断售后类型
			MoneyBusinessType moneyBusinessType=
					moneyBusinessTypeService.selectMoneyBusinessByTypeId(16);//退货返还妆币
		   	CUserPointTransaction UserPoint=new CUserPointTransaction();
		   	UserPoint.setUserId(saveModel.getUserId());
		   	OrderInfo  info=orderInfoMapper.selectByPrimaryKey(saveModel.getOrderInfoId());
		   	UserPoint.setOrderSn(info==null?null:info.getOrderSn());
		   	UserPoint.setOrderDetailId(saveModel.getOrderDetailId());
		   	UserPoint.setOrderObjectId(saveModel.getOrderObjectId());
		   	UserPoint.setBusinessSourceId(afterSales.getId()); 
		   	UserPoint.setBusinessTypeId(moneyBusinessType.getTypeId());
		   	UserPoint.setBusinessTypeName(moneyBusinessType.getTypeName());
		   	UserPoint.setAmount((long)saveModel.getRefundCashMoney());
		   	UserPoint.setTransactionStatus(-1); //新建
		   	UserPoint.setIsCustom(0);//非手工
		   	UserPoint.setIsDelete(0);//没有被删除
		   	int count=pointTransactionMapper.insertSelective(UserPoint);
			if(count<=0){
				logger.error("----->添加积分事务失败,子订单号:"+saveModel.getOrderDetailId());
			}
		}
		if (auto == false) {
			/**
			 * 冻结订单
			 */
			int applyType = 0;
			if (saveModel.getIsRefund() == 2) {
				applyType = 1;
			}
			orderStatusInWMS(saveModel.getOrderInfoSn(),applyType,saveModel.getCustomerServiceNumber(),saveModel.getProductBn());
		}
	}

	/**
	 * 提交申诉
	 * @throws Exception 
	 */
	@Override
	public ResponseEntity<?> saveAfterSaleComplaint(RequestAfterSalesModel model) throws Exception {
		// TODO Auto-generated method stub
		int updateStatus = afterSalesMapper.updateAfterSalesTypeToComplaint(model.getType(),
				model.getSupplementaryReason(), model.getAfterSalesId(), model.getUserRefundReason(),
				model.getImgProof1(), model.getImgProof2(), model.getImgProof3(),model.getIsRefund());
		if (updateStatus <= 0) {
			throw new Exception("更新售后单失败");
		}
		// 修改父订单、子订单、订单详情为售后中   修改父订单的售后开始时间
		/*int upStatus = orderDetailMapper.updateOrderDetailToRefund(afterSales.getOrderObjectId(),
				afterSales.getOrderInfoId(), afterSales.getOrderDetailId(), DateUtil.toDateStr(new Date()));
		if (upStatus <= 0) {
			throw new Exception();
		}*/
		
		// 分佣开关关闭
		AfterSales afterSales = afterSalesMapper.selectAfterSalesByPrimyKey(model.getAfterSalesId());
		int close = orderDetailMapper.updateOrderDetailToRefund(afterSales.getOrderObjectId(),
				afterSales.getOrderInfoId(), afterSales.getOrderDetailId());
		if (close <= 0) {
			throw new Exception();
		}
		
		/**
		 * 冻结订单
		 */
		int applyType = 0;
		if (model.getIsRefund() == 2) {
			applyType = 1;
		}
		orderStatusInWMS(afterSales.getOrderInfoSn(), applyType, afterSales.getCustomerServiceNumber(), afterSales.getProductBn());

		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	/**
	 * 查询所有售后中的订单
	 */
	@Override
	public ResponseEntity<?> findAfterSalesByUserId(RequestAfterSalesModel model) {
		// TODO Auto-generated method stub
		List<AfterSales> list = afterSalesMapper.selectAfterSalesByUserId(model.getUserId(),model.getStartIndex(),model.getPageSize());
		if(list.size() <= 0){
			List<ResponseAfterSalesListModel> resList = new ArrayList<ResponseAfterSalesListModel>();
			return new ResponseEntity<>(new ResponseResultModel<>(resList), HttpStatus.OK);
		}
		List<ResponseAfterSalesListModel> resList = new ArrayList<ResponseAfterSalesListModel>();
		for(AfterSales afterSales : list){
			ResponseAfterSalesListModel resModel = new ResponseAfterSalesListModel();
			OrderDetail orderDetail = orderDetailMapper.selectByPrimaryKey(afterSales.getOrderDetailId());
			resModel.setAfterSalesId(afterSales.getId());
			resModel.setCustomerServiceNumber(afterSales.getCustomerServiceNumber());
			resModel.setGoodsName(orderDetail.getGoodName());//放入商品名称
			resModel.setGoodImg(orderDetail.getNavigateImg1());//放入商品导航图
			resModel.setGoodSpecInfo(orderDetail.getSpecName());//放入商品规格信息
			resModel.setRefundCashMoney(orderDetail.getCashCoin());//实际使用的现金币
			resModel.setRefundBalancePaid(orderDetail.getBalancePaid());//实际使用的余额
			resModel.setRefundMoney(orderDetail.getTotalFee());//实际支付的现金
			resModel.setIsRefund(afterSales.getIsRefund());
			resModel.setStatus(afterSales.getStatus());
			resModel.setQuantity(afterSales.getQuantity());//商品数量
			resModel.setCourierCompany(afterSales.getCourierCompany());
			resModel.setCourierNumber(afterSales.getCourierNumber());
			resModel.setCourierCompanyEn(afterSales.getCourierCompanyEn());
			resModel.setType(afterSales.getType());
			resModel.setSendBack(afterSales.getSendBack());
			resList.add(resModel);
		}
		return new ResponseEntity<>(new ResponseResultModel<>(resList), HttpStatus.OK);
	}

	/**
	 * 查询售后订单详情
	 */
	@Override
	public ResponseEntity<?> findAfterSalesById(Long afterSalesId) {
		ResponseAfterSalesSuccess resModel = new ResponseAfterSalesSuccess();
		AfterSales afterSales = afterSalesMapper.selectAfterSalesByPrimyKey(afterSalesId);
		if(afterSales == null){
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
		}
		if(afterSales.getIsRefund() == 2 && afterSales.getStatus() != 4){
			StoreRefundAddress address = storeRefundAddressMapper.selectStoreRefundAddressByStoreId(afterSales.getStoreId());
			ResponseStoreRefundAddress resAddress = new ResponseStoreRefundAddress();
			resAddress.setStoreId(address.getStoreId());
			resAddress.setProvince(address.getProvince());
			resAddress.setCity(address.getProvince());
			resAddress.setArea(address.getArea());
			resAddress.setAddress(address.getAddress());
			resAddress.setLinkMan(address.getLinkMan());
			resAddress.setMobile(address.getMobile());
			resModel.setAddress(resAddress);
			resModel.setCourierCompany(afterSales.getCourierCompany());
			resModel.setCourierNumber(afterSales.getCourierNumber());
		}
		OrderDetail orderDetail = orderDetailMapper.selectByPrimaryKey(afterSales.getOrderDetailId());
		List<ResponseReason> resReason = new ArrayList<ResponseReason>();
		resModel.setRefundReason(resReason);
		resModel.setAfterSalesId(afterSales.getId());
		resModel.setCustomerServiceNumber(afterSales.getCustomerServiceNumber());
		resModel.setGoodsName(orderDetail.getGoodName());//放入商品名称
		resModel.setGoodImg(orderDetail.getNavigateImg1());//放入商品导航图
		resModel.setGoodSpecInfo(orderDetail.getSpecName());//放入商品规格信息
		resModel.setRefundCashMoney(orderDetail.getCashCoin());//实际使用的妆币
		resModel.setRefundBalancePaid(orderDetail.getBalancePaid());//实际使用的余额
		resModel.setRefundMoney(orderDetail.getTotalFee());//实际支付的现金
		resModel.setImgProof1(afterSales.getImgProof1());
		resModel.setImgProof2(afterSales.getImgProof2());
		resModel.setImgProof3(afterSales.getImgProof3());
		resModel.setCreateTime(afterSales.getCreateTime());
		resModel.setIsRefund(afterSales.getIsRefund());
		resModel.setStatus(afterSales.getStatus());
		resModel.setQuantity(afterSales.getQuantity());
		resModel.setUserRefundReason(afterSales.getUserRefundReason());
		resModel.setType(afterSales.getType());
		resModel.setSendBack(afterSales.getSendBack());
		resModel.setCourierCompanyEn(afterSales.getCourierCompanyEn());
		if (afterSales.getUserFirstReason() == null) {
			resModel.setUserFirstReason("");
		} else {
			resModel.setUserFirstReason(afterSales.getUserFirstReason());
		}
		if (afterSales.getSupplementaryReason() == null) {
			resModel.setSupplementaryReason("");
		} else {
			resModel.setSupplementaryReason(afterSales.getSupplementaryReason());
		}
		if(afterSales.getStatus() == 4){
			// resModel.setStatus("已拒绝");
			if(afterSales.getType() == 1){
				resModel.setStoreRefuseReason(afterSales.getStoreRefuseReason());
			} else {
				resModel.setStoreRefuseReason(afterSales.getStoreRefuseReason1());
			}
		}
		return new ResponseEntity<>(new ResponseResultModel<ResponseAfterSalesSuccess>(resModel), HttpStatus.OK);
	}
	
	/**
	 * 修改图片凭证
	 */
	@Override
	public ResponseEntity<?> changeImagePools(RequestAfterSalesModel model) throws Exception {
		// TODO Auto-generated method stub
		if(model.getImgIndex() > 3 || model.getImgIndex() == 0){
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
		}
		int updateStatus = afterSalesMapper.updateImagePoolsByIndex(model.getImgIndex(),model.getImgUrl(),model.getAfterSalesId());
		if(updateStatus <= 0){
			throw new Exception();
		}
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	/**
	 * 填写回寄信息
	 */
	@Override
	public ResponseEntity<?> fillInTheDeliveryInformation(RequestAfterSalesModel model) throws Exception {
		// TODO Auto-generated method stub
		AfterSales afterSale = afterSalesMapper.selectAfterSalesByPrimyKey(model.getAfterSalesId());
		
		int updateStatus = afterSalesMapper.updateCourierInformation(model.getAfterSalesId(), model.getCourierCompany(), model.getCourierCompanyEn(), model.getCourierNumber());
		if(updateStatus <= 0){
			throw new Exception();
		}
		
		if (afterSale.getHistory() == 1) {
			if (afterSale.getReturnOrderId() == null && "".equals(afterSale.getReturnOrderId())) {
				/**
				 * OMS交互
				 */
				if (afterSale.getHistory() == 1) {
					addReturnOrder(afterSale.getQuantity(), afterSale.getProductBn(), afterSale.getOrderInfoSn(), afterSale.getCustomerServiceNumber(), model.getCourierCompanyEn(), model.getCourierNumber());
				}
			}
		}
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	/**
	 * 发起申诉
	 */
	@Override
	public ResponseEntity<?> launchComplaintApplication(Long afterSalesId) throws Exception {
		// TODO Auto-generated method stub
		ResponseAfterSalesSuccess resModel = new ResponseAfterSalesSuccess();
		AfterSales afterSales = afterSalesMapper.selectAfterSalesByPrimyKey(afterSalesId);
		if(afterSales == null){
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
		}
		if(afterSales.getIsRefund() == 2 && afterSales.getStatus() != 4){
			StoreRefundAddress address = storeRefundAddressMapper.selectStoreRefundAddressByStoreId(afterSales.getStoreId());
			ResponseStoreRefundAddress resAddress = new ResponseStoreRefundAddress();
			resAddress.setStoreId(address.getStoreId());
			resAddress.setProvince(address.getProvince());
			resAddress.setCity(address.getProvince());
			resAddress.setArea(address.getArea());
			resAddress.setAddress(address.getAddress());
			resAddress.setLinkMan(address.getLinkMan());
			resAddress.setMobile(address.getMobile());
			resModel.setAddress(resAddress);
			resModel.setCourierCompany(afterSales.getCourierCompany());
			resModel.setCourierNumber(afterSales.getCourierNumber());
			resModel.setCourierCompanyEn(afterSales.getCourierCompanyEn());
		}
		OrderDetail orderDetail = orderDetailMapper.selectByPrimaryKey(afterSales.getOrderDetailId());
		//获取退款理由
		List<RefundReason> reasons = refundReasonMapper.selectRefundReasonByType(orderDetail.getStatus());
		List<ResponseReason> resReason = new ArrayList<ResponseReason>();
		for(RefundReason reason : reasons){
			ResponseReason resRea = new ResponseReason();
			resRea.setReason(reason.getReason());
			resRea.setType(reason.getType());
			resReason.add(resRea);
		}
		resModel.setRefundReason(resReason);
		resModel.setAfterSalesId(afterSales.getId());
		resModel.setCustomerServiceNumber(afterSales.getCustomerServiceNumber());
		resModel.setGoodsName(orderDetail.getGoodName());//放入商品名称
		resModel.setGoodImg(orderDetail.getNavigateImg1());//放入商品导航图
		resModel.setGoodSpecInfo(orderDetail.getSpecName());//放入商品规格信息
		resModel.setRefundCashMoney(orderDetail.getCashCoin());//实际使用的现金币
		resModel.setRefundBalancePaid(orderDetail.getBalancePaid());//实际使用的余额
		resModel.setRefundMoney(orderDetail.getTotalFee());//实际支付的现金
		resModel.setImgProof1(afterSales.getImgProof1());
		resModel.setImgProof2(afterSales.getImgProof2());
		resModel.setImgProof3(afterSales.getImgProof3());
		resModel.setCreateTime(afterSales.getCreateTime());
		resModel.setIsRefund(afterSales.getIsRefund());
		resModel.setStatus(afterSales.getStatus());
		resModel.setQuantity(afterSales.getQuantity());
		resModel.setUserRefundReason(afterSales.getUserRefundReason());
		resModel.setType(afterSales.getType());
		resModel.setSendBack(afterSales.getSendBack());
		if (afterSales.getUserFirstReason() == null) {
			resModel.setUserFirstReason("");
		} else {
			resModel.setUserFirstReason(afterSales.getUserFirstReason());
		}
		if(afterSales.getStatus() == 4){
			// resModel.setStatus("已拒绝");
			if(afterSales.getType() == 1){
				resModel.setStoreRefuseReason(afterSales.getStoreRefuseReason());
			} else {
				resModel.setStoreRefuseReason(afterSales.getStoreRefuseReason1());
			}
		}
		return new ResponseEntity<>(new ResponseResultModel<ResponseAfterSalesSuccess>(resModel), HttpStatus.OK);
	}

	/**
	 * 退款完成处理售后单接口
	 * @author gaoweiqi
	 * @date 2017年8月19日 12:44:05
	 */
	@Override
	public void userRefundSuccess(AfterSales afterSale) throws Exception {
		// 本次售后综合时间   分钟
		// 当前时间    - 开始时间
		int timeMillin = (int) ((new Date().getTime() - (DateUtil.parse(afterSale.getCreateTime()).getTime()))/1000/60);
		
		UserMoney userAmount = userMoneyMapper.selectByTypeIDAndUserID(afterSale.getUserId(),
				1);// 账户余额
		UserMoney userPoint = userMoneyMapper
				.selectByTypeIDAndUserID(afterSale.getUserId(), 2);// 账户积分
		if (userAmount == null || userPoint == null) {
			return ;// 账户信息找不到 找不全
		}
		OrderDetail orderDetail = orderDetailMapper.selectByPrimaryKey(afterSale.getOrderDetailId());
		OrderObject orderObj = orderObjectMapper.selectOrderObjectById(afterSale.getOrderObjectId());
		// 更改售后的状态为完成
		int updateAfterStatus = afterSalesMapper.updateAfterSalesStatusById(afterSale.getId(), 3,afterSale.getRefundId());
		if(updateAfterStatus <= 0){
			logger.error("------>状态更改异常："+afterSale.getOrderDetailId());
		}
		
		//关闭评论
		goodsCommentMapper.updateGoodsCommentCloseByOrderDetailId(afterSale.getOrderDetailId());
		
		// 归还妆币和余额付
		int updateMoneyStatus =
		userMoneyService.refundUserMoneyAndPointByAfterSaleSourceID(afterSale.getUserId(),
				afterSale.getRefundCashMoney(),16, afterSale.getRefundBalancePaid(),7,afterSale.getId(),orderDetail.getStoreId());
		if (updateMoneyStatus <= 0) {
			logger.error("------>返还现金币和余额失败，订单详情ID："+afterSale.getOrderDetailId());
		}

		if (afterSale.getRefundCashMoney() > 0) {
			UserJournal userJournal = new UserJournal();
			userJournal.setUserId(afterSale.getUserId());
			userJournal.setStatus(6);// 状态设置为系统返还
			userJournal.setMoney(afterSale.getRefundCashMoney());
			userJournal.setOrderSn(afterSale.getOrderInfoSn());
			userJournal.setBankId(0);
			userJournal.setType("+");
			userJournal.setComment("退款返还");
			int insertStatus = userBankMapper.insertUserJournal(userJournal);
			if (insertStatus <= 0) {
				logger.error("------>添加系统日志失败，订单详情ID："+afterSale.getOrderDetailId());
			}
		}
		// 处理已经生成的分佣和消费积分
		int[] balanceAccountsType={5,7};//余额记账
		int[] pointAccountsType={14,16};//妆币记账
		// 处理已经生成的分佣
		 List<Commision> commList=commisionMapper.selectByDetailID(afterSale.getOrderDetailId());
		 List<Commision> EarningCommList=new ArrayList<Commision>();//用于计算收益
		 boolean calculateEarning=false;//是否计算收益
		 int beforeSize=commList.size();
		 //处理佣金
		 for(Commision c:commList){
			// int i=0;
			 Commision cTemp=new Commision();
			 BeanUtils.copyProperties(c,cTemp);
			 cTemp.setFee(0-c.getFee().intValue());
			 cTemp.setId(null);
			 cTemp.setCreateTime(null);
			 cTemp.setUpdateTime(null);
			 cTemp.setResultTime(null);
			 commisionMapper.insertSelective(cTemp);
			 EarningCommList.add(cTemp);
		 }
		 commList=commisionMapper.selectByDetailID(afterSale.getOrderDetailId());
		 if(orderDetail!=null&&(beforeSize*2==commList.size())&&commList.size()>0){//有订单明细 正负向数量相等 开始处理佣金事务 
			 int i=commisionMapper.updateResultInId(commList,DateUtil.getNow());//处理佣金
			 if(i==commList.size()){
				 for(Commision c:commList){
		    			// 处理事务成功 插入流水
						UserJournal balanceJournal=new UserJournal();
						balanceJournal.setUserId(c.getUserId()); 
						balanceJournal.setOrderSn(String.valueOf(afterSale.getId())); //售后单ID
						balanceJournal.setMoney(c.getFee()>0?c.getFee():0-c.getFee().intValue()); 
						balanceJournal.setType(c.getFee()>0?"+":"-");
						balanceJournal.setComment(c.getFee()>0?"售后正向处理":"售后负向抵消");
						balanceJournal.setStatus(6);//系统返还
						balanceJournal.setBusinessTypeId(c.getBusinessTypeId());
						balanceJournal.setBusinessTypeName(c.getBusinessTypeName()); 
						balanceJournal.setIsDelete(0);
						balanceJournal.setCommisionId(c.getId().intValue());
						balanceJournal.setExtend3(c.getExtend3());
						String KeepAccountsType="";
					    //获取佣金的账务类型
						if(orderDetail.getStoreId().intValue()==StoreTypeEnum.T14.getCode()){
							KeepAccountsType=KeepAccountsTypeConstants.COMMISSION_SKIN79;
						}else{
							KeepAccountsType=KeepAccountsTypeConstants.COMMISSION_NOSKIN79;
						}
						if(ArrayUtils.contains(balanceAccountsType, balanceJournal.getBusinessTypeId())){//余额消费
							KeepAccountsType=KeepAccountsTypeConstants.COMMISSION_PAYMENT;
						}
						balanceJournal.setKeepAccountsType(KeepAccountsType);
						userJournalMapper.insertSelective(balanceJournal);
						
						UserJournal ResultBalanceJournal=
							userJournalMapper.getUserJournalBySourceIDandBusinessType(
									c.getId(),c.getBusinessTypeId());
						if(ResultBalanceJournal!=null){//生成流水成功
							userAmount = userMoneyMapper.selectByTypeIDAndUserID(afterSale.getUserId(),
									1);// 实时账户余额
							// 记录用户资产的变化
							CUserMoneyChange MoneyChange = new CUserMoneyChange();
							MoneyChange.setUserId(ResultBalanceJournal.getUserId());
							MoneyChange.setOrderSn((long)ResultBalanceJournal.getId());// 源ID
							MoneyChange.setChangeAmount(
						"+".equals(ResultBalanceJournal.getType())?ResultBalanceJournal.getMoney():0-ResultBalanceJournal.getMoney());
							MoneyChange.setNormalBeforAmount(userAmount.getNormalAmount());
							MoneyChange.setNormalAfterAmount(userAmount.getNormalAmount()
									+ MoneyChange.getChangeAmount());
							MoneyChange.setSourceType(Byte.valueOf("1"));//amount
							MoneyChange.setFreeBeforAmount(userAmount.getFrozenAmount());
							MoneyChange.setFreeAfterAmount(userAmount.getFrozenAmount());
							MoneyChange.setChangeFreeAmount(0);
							moneyChangeMapper.insertSelective(MoneyChange);
							// 增加账户amount
							userMoneyMapper.increaseUserAmount(
									ResultBalanceJournal.getUserId(), 1,
						"+".equals(ResultBalanceJournal.getType())?ResultBalanceJournal.getMoney():0-ResultBalanceJournal.getMoney());
						}
		            }
			 }
			 calculateEarning=true;//需要重新计算收益
		 }
         //处理已经生成的消费积分
		 List<CUserPointTransaction> listPoint=
				 pointTransactionMapper.selectByOrderDetailID(afterSale.getOrderDetailId());
		 beforeSize=listPoint.size();
		 for(CUserPointTransaction c:listPoint){
			 CUserPointTransaction CPoint=new CUserPointTransaction();
			 BeanUtils.copyProperties(c, CPoint);
			 CPoint.setId(null);
			 CPoint.setAmount(CPoint.getAmount()==null?0L:0L-CPoint.getAmount().longValue());
			 CPoint.setBusinessTime(null);
			 CPoint.setCreateTime(null);
			 pointTransactionMapper.insertSelective(CPoint);
		 }	
		 listPoint=
				 pointTransactionMapper.selectByOrderDetailID(afterSale.getOrderDetailId());
		 if(orderDetail!=null&&(beforeSize*2==listPoint.size())&&listPoint.size()>0){//有订单明细 正负向数量相等 开始处理佣金事务 
			 int i= pointTransactionMapper.updateCommisionResultInId(listPoint);
			if(i==listPoint.size()){
				for(CUserPointTransaction UserPointTransaction:listPoint){
					// 处理事务成功 插入流水
					UserPointJournal pointJournal = new UserPointJournal();
					pointJournal.setValueByPointTransaction(UserPointTransaction);// 积分事务到积分记录表
					pointJournal.setBusinessSourceId(UserPointTransaction.getId());//业务源单ID
					String KeepAccountsType="";
				    //获取佣金的账务类型
					if(orderDetail.getStoreId().intValue()==StoreTypeEnum.T14.getCode()){
						KeepAccountsType=KeepAccountsTypeConstants.POINT_SKIN79;
					}else{
						KeepAccountsType=KeepAccountsTypeConstants.POINT_NOSKIN79;
					}
					if(pointJournal.getBusinessTypeId()!=null&&ArrayUtils.contains(pointAccountsType, pointJournal.getBusinessTypeId().intValue())){//妆币消费
						KeepAccountsType=KeepAccountsTypeConstants.POINT_PAYMENT;
					}
					pointJournal.setKeepAccountsType(KeepAccountsType);// 财务记账类型
					userPointJournalMapper.insertSelective(pointJournal);

					UserPointJournal ResultPointJournal =
						userPointJournalMapper.selectBySourceIDAndBusinessType(
							UserPointTransaction.getId(), pointJournal.getBusinessTypeId());
					if(ResultPointJournal!=null){//查到对应的处理记录了
						userPoint = userMoneyMapper.selectByTypeIDAndUserID(afterSale.getUserId(), 2);// 实时账户积分
						// 记录用户资产的变化
						CUserMoneyChange MoneyChange = new CUserMoneyChange();
						MoneyChange.setUserId(ResultPointJournal.getUserId());
						MoneyChange.setOrderSn(ResultPointJournal.getId());// 源ID
						MoneyChange.setChangeAmount(ResultPointJournal.getAmount().intValue());
						MoneyChange.setNormalBeforAmount(userPoint.getNormalAmount());
						MoneyChange.setNormalAfterAmount(userPoint.getNormalAmount()
								+ResultPointJournal.getAmount().intValue());
						MoneyChange.setSourceType(Byte.valueOf("2"));// 积分
						MoneyChange.setFreeBeforAmount(userPoint.getFrozenAmount());
						MoneyChange.setFreeAfterAmount(userPoint.getFrozenAmount());
						MoneyChange.setChangeFreeAmount(0);
						moneyChangeMapper.insertSelective(MoneyChange);
						// 增加账户妆币
						userMoneyMapper.increaseUserAmount(
								UserPointTransaction.getUserId(), 2,
								UserPointTransaction.getAmount());
					}
			 }
			}
		 }
		 
		//关闭订单
			int codeJude = orderStatusService.closeOrder(orderDetail);
			// 分佣开关的控制
			if (codeJude == 10000) {
				// 说明有有效订单可以继续分佣
				int updateObjFlagStatus = orderObjectMapper.updateOrderObjectRefundByFlag(afterSale.getOrderObjectId());
				if (updateObjFlagStatus <= 0) {
//					 throw new Exception();
				}
				// 放入分佣时间
				int updateRefundTime = orderObjectMapper.updateRefundTimeById(afterSale.getOrderObjectId(),timeMillin);
				if (updateRefundTime <= 0) {
					// throw new Exception();
				}
			}
        // 订单关闭后需要计算收益
        if (calculateEarning) {
            afterSaleEarning(orderDetail, EarningCommList, orderObj);
        }
			//订单全部关闭 需要返还红包
			if(codeJude==1&&orderObj.getRedPacketId()>0){
				redPacketBiz.backRedPacket(new BackRedPacketRequest(2,orderObj.getRedPacketOwnerId(),true));
			}
			
		 
		//查看info订单到底是否是关闭状态
	OrderInfo	OrderInfo=
		orderInfoMapper.selectByPrimaryKey(orderDetail.getOrderId());
//		int i=	OrderInfo.getTotalFee()==null?0:OrderInfo.getTotalFee().intValue();
//	    int j=    OrderInfo.getFreight()==null?0:OrderInfo.getFreight().intValue();
	    int freight_amount=OrderInfo.getFreight()==null?0:OrderInfo.getFreight().intValue();
	   if(OrderInfo!=null&&(OrderInfo.getStatus()==OrderStatusEnum.S7.getCode())
			   &&afterSale.getIsRefund()==1){//单子交易关闭 仅退款 现在考虑要不要退运费
	   	   List<OrderDetail> ListDetail= orderDetailMapper.selectOrderDetailEntityByOrderInfoId(OrderInfo.getId());
	   	   boolean iscanelFreight=true;
	   	   for(OrderDetail d:ListDetail){
	   		   if(d.getStatus()!=OrderStatusEnum.S7.getCode()){
	   			iscanelFreight=false;
	   			break;
	   		   }
	   	   }
	   	   if(iscanelFreight){//开始退运费
	   			if(OrderInfo.getFreight()!=null&&OrderInfo.getFreight().intValue()>0){//还有剩余的钱需要开始退款
	   			boolean tt=refundFreight(afterSale);//退运费
	   			if(!tt){
	   				freight_amount=0;	   				
	   				logger.error("------>返还运费失败，订单详情ID："+afterSale.getOrderDetailId());
	   			}
	   		   }
	   	   }
	   }	
		// 取消已经生成的结算信息
		int updateOrderSettlementStatus = orderSettlementMapper.updateOrderSettlementStatusByOrderDetailId(afterSale.getOrderDetailId());
		if (updateOrderSettlementStatus <= 0) {
			logger.error("------>取消结算信息失败，订单详情ID："+afterSale.getOrderDetailId());
		}
		
		/**
		 * OMS交互
		 */
		if (afterSale.getHistory() == 1) {
			if ("".equals(afterSale.getReturnOrderId()) || afterSale.getReturnOrderId() == null) {
				// 通知OMS取消仅退款的订单
				freezeOrder(afterSale.getProductBn(), afterSale.getOrderInfoSn(), afterSale.getCustomerServiceNumber(), orderDetail,0,freight_amount);
			} else {
				/**
				 * OMS交互 通知退货退款的订单
				 */
				addRefundOrder(afterSale.getProductBn(), afterSale.getOrderInfoSn(),
						afterSale.getCustomerServiceNumber(), orderDetail, afterSale.getReturnOrderId(),
						afterSale.getCreateTime());
			}
		}
		
		// 推送消息
		PushMessage pushMessage = new PushMessage();
		pushMessage.setIsAll(0);
		pushMessage.setUserId(afterSale.getUserId());
		pushMessage.setStatus(1);
		pushMessage.setTitle("您申请的退款已成功处理");
		pushMessage.setContent("您的售后订单："+afterSale.getCustomerServiceNumber()+"，已经成功处理，到账时间为3-7天，请注意查收。");
		pushMessage.setType(1);
		pushMessageService.autoPushMessage(pushMessage);
		
	}
		
	private void afterSaleEarning(OrderDetail orderDetail, List<Commision> earningCommList,OrderObject order) {
		try {
			Map<Long, Integer> earningMap = new HashMap<Long, Integer>();
			for (Commision commision : earningCommList) {
				Long userID = commision.getUserId();
				Integer Fee = commision.getFee();
				if (Fee < 0) {// 负向收益
					if (earningMap.containsKey(userID)) {
						earningMap.put(userID, earningMap.get(userID) + Fee);
					} else {
						earningMap.put(userID, Fee);
					}
				}
			}
			userEarningsService.CalculateEarningsAfterSaleWithCache(earningMap,order.getOpenStoreUserId(),
					-(orderDetail.getTotalFee()+orderDetail.getBalancePaid()),
					order.getPayTime());
		} catch (Exception e) {
			logger.error("计算售后负向收益失败 ：商品订单ID:{} 错误:{}", orderDetail.getId(), e.getMessage());
		}
	}

	/**
	* <dl>
	* <dt>售后单处理返还运费 仅处理已退款的 不处理退货退款的</dt>
	* </dl>
	* @param afterSales
	* @return boolean
	* @author gaoweiqi
	* @date 2017年9月12日 16:44:05
	*/
	public boolean refundFreight(AfterSales afterSales) {
		try {
			OrderObject orderObject = orderService2.selectOrderObjectByOrderObjectId(afterSales.getOrderObjectId());	
							List<OrderPay> PayList=
						orderPayMapper.selectPaySuccessByOrderSn(orderObject.getOrderSn(),orderObject.getPayType());
							OrderInfo info= orderInfoMapper.selectByPrimaryKey(afterSales.getOrderInfoId());
							if(info==null||info.getId()==null)
								return false;
							Long orderID=0-info.getId().longValue();
							OrderSettlement settlement = orderSettlementMapper
									.selectByOrderDetailId(orderID);
							if(settlement==null){
								logger.error("------>未找到运费的分账信息 (10.20号之前的0元付单子没有分账信息) 相关订单号:"+
										info.getId());
								return  false;
							}
							String divideString =orderService2.selectFreightDivideString(settlement);
							Integer freight=settlement.getTotalFee();//实付运费
							Integer Coinfreight=settlement.getCashCoin();//妆币运费
							Integer Balancefreight=settlement.getBalancePaid();//余额运费
							int [] YeePayType={20,21,22,23,24};//易宝支付
							
							if(PayList!=null&&PayList.size()>0&&freight!=null&&freight>0){
							//开始退运费
							OrderPay OrderPay=PayList.get(0);
							if(ArrayUtils.contains(YeePayType,OrderPay.getPayType())){//易宝退款
								if ("FAIL".equals(divideString)) {
									logger.error("------>运费分账信息的状态码不对，相关订单号:"+
											info.getId());
									return false;
								}
								// 构建请求易宝的参数
								String freightSn = "F" + OrderUtil.getOrderSn();//请求号
								String appKey = this.baseRestrictionsService.getBaseRestrictionsForCache("app_key").getName();
								Map<String,Object> map = new HashMap<String, Object>();
								map.put("amount", ((freight.doubleValue()) / 100) + "");
								map.put("orderrequestid", OrderPay.getPaySn());
								map.put("requestid",freightSn);
								map.put("divideinfo", divideString);
								map.put("memo", "售后仅退货款(运费款)");
								map.put("method", "yeepay.trade.refund");
								map.put("app_key", appKey);
								map.put("format", "json");
								map.put("timestamp", sdf.format(new Date()));
								String requestUrl = baseRestrictionsService.getBaseRestrictionsForCache("yeeRefund_url").getName();
								JSONObject resultJson = JSONObject.parseObject(HttpUtil.post(requestUrl,map));
								map.put("responseJSON", resultJson.toJSONString());
								if (resultJson.getJSONObject("error_response") != null) {
									logger.error("------>"+resultJson.getJSONObject("error_response"));
									return  false;
								}
								if (resultJson.getJSONObject("yeepay_trade_refund_response")!=null&&
									"1".equals(resultJson.getJSONObject("yeepay_trade_refund_response").getString("code"))) {
									afterSalesMapper.updateAfterSalesByID(afterSales.getId(),map.toString(),
											resultJson.getJSONObject("yeepay_trade_refund_response").getString("refundexternalid"),freight);
		 							// 取消已经生成的运费结算信息
		 							int updateOrderSettlementStatus = orderSettlementMapper.updateOrderSettlementStatusByOrderDetailId(orderID);
		 							if (updateOrderSettlementStatus <= 0) {
		 								logger.error("------>取消结算信息失败，订单详情ID："+orderID);
		 							}
								} else {
									logger.error("------>售后单易宝退款失败，订单详情ID："+orderID);
									return  false;
								}				
							}
							//支付宝运费退款
							if(OrderPay.getPayType() == PayTypeEnum.T2.getCode().intValue()){
								AlipayAppKeyInfo alipayAppKeyInfo = new AlipayAppKeyInfo();
								alipayAppKeyInfo.setSellerId(AlipayConfig.sellerId);
								alipayAppKeyInfo.setAppId(AlipayConfig.appId);
								alipayAppKeyInfo.setPid(AlipayConfig.pid);
								alipayAppKeyInfo.setAppPrivateKey0(AlipayConfig.appPrivateKey0);
								alipayAppKeyInfo.setAlipayPublicKey0(AlipayConfig.alipayPublicKey0);
								alipayAppKeyInfo.setAppPrivateKey(AlipayConfig.appPrivateKey);
								alipayAppKeyInfo.setAlipayPublicKey(AlipayConfig.alipayPublicKey);
								alipayAppKeyInfo.setUrl(AlipayConfig.url);
								alipayAppKeyInfo.setCallbackUrl(AlipayConfig.callbackUrl);
								alipayAppKeyInfo.setStoreName(AlipayConfig.storeName);
								String liushuiID="A" + OrderUtil.getOrderSn();
								AlipayTradeRefundResponse response = alipay.alipayRefund(alipayAppKeyInfo, OrderPay.getPaySn(),
										orderObject.getPayId(), freight.longValue(),liushuiID);
								if (response.isSuccess()) {
									if(response.getFundChange().equals("Y")){
										afterSalesMapper.updateAfterSalesByID(afterSales.getId(),"支付宝退运费请求号:"+liushuiID,"支付宝无退款流水",freight);
			 							// 取消已经生成的运费结算信息
			 							int updateOrderSettlementStatus = orderSettlementMapper.updateOrderSettlementStatusByOrderDetailId(orderID);
			 							if (updateOrderSettlementStatus <= 0) {
			 								logger.error("------>取消结算信息失败，订单详情ID："+orderID);
			 							}
									}
								}else{
									logger.error("------>支付宝退运费失败，订单详情ID："+orderID);
									return  false;
								}
							}
							//微信退款 微信 公众号支付
							if(OrderPay.getPayType() == PayTypeEnum.T1.getCode().intValue()||OrderPay.getPayType() == PayTypeEnum.T3.getCode().intValue()){
								PayAppKeyInfo payAppKeyInfo = new PayAppKeyInfo();
								if (OrderPay.getPayType() == PayTypeEnum.T1.getCode()) {
									payAppKeyInfo.setAppId(PayConfig.appId0);
									payAppKeyInfo.setSecret(PayConfig.secret0);
									payAppKeyInfo.setPartnerId(PayConfig.partnerId0);
									payAppKeyInfo.setPartnerKey(PayConfig.partnerKey0);
									payAppKeyInfo.setCallbackUrl(PayConfig.callbackUrl);
									payAppKeyInfo.setStoreName(PayConfig.storeName);
									payAppKeyInfo.setCa(PayConfig.ca0);
								} else if (OrderPay.getPayType() == PayTypeEnum.T3.getCode()) {
									payAppKeyInfo.setAppId(PayConfig.appId);
									payAppKeyInfo.setSecret(PayConfig.secret);
									payAppKeyInfo.setPartnerId(PayConfig.partnerId);
									payAppKeyInfo.setPartnerKey(PayConfig.partnerKey);
									payAppKeyInfo.setCallbackUrl(PayConfig.callbackUrl);
									payAppKeyInfo.setStoreName(PayConfig.storeName);
									payAppKeyInfo.setCa(PayConfig.ca);
								}
								String liushuiID="A" + OrderUtil.getOrderSn();
								Map<String, Object> outmap = getWeChat(OrderPay.getPayType()).weChaPayRefund(payAppKeyInfo, OrderPay.getPaySn(),
										orderObject.getTotalFee(), freight,liushuiID, orderObject.getPayId());
								if ("SUCCESS".equals(outmap.get("return_code"))) {
									String refundId = outmap.get("refund_id").toString(); //微信的退款号
									afterSalesMapper.updateAfterSalesByID(afterSales.getId(),outmap.toString(),refundId,freight);
		 							// 取消已经生成的运费结算信息
		 							int updateOrderSettlementStatus = orderSettlementMapper.updateOrderSettlementStatusByOrderDetailId(orderID);
		 							if (updateOrderSettlementStatus <= 0) {
		 								logger.error("------>取消结算信息失败，订单详情ID："+orderID);
		 							}
								}else{
									logger.error("------>微信退运费失败，订单详情ID："+orderID);
									return  false;
								}
							}
						}
						if(!refundFreightCommissionAndPoint(afterSales, Coinfreight, Balancefreight)){//退运费失败
							logger.error("------>退运费失败，订单详情ID："+orderID);
							return false;
						}
						} catch (Exception e) {
							logger.error("------>售后单处理返还运费："+e.getMessage());
							return  false;
						}
		return true;
		}
	/**
	 * <dl>
	 * <dt>建立运费的事务 流水</dt>
	 * </dl>
	 * @param afterSales
	 * @return boolean
	 * @author gaoweiqi
	 * @date 2017年10月18日 15:44:05
	 */
	public boolean refundFreightCommissionAndPoint(AfterSales afterSales,Integer Coinfreight,Integer Balancefreight) {
		  //余额付不为空 生成事务插入到余额事务表中
		User user = userMapper.selectByPrimaryKey(afterSales.getUserId());// 当前用户
		UserMoney userAmount = userMoneyMapper.selectByTypeIDAndUserID(afterSales.getUserId(),
				1);// 账户余额
		UserMoney userPoint = userMoneyMapper
				.selectByTypeIDAndUserID(afterSales.getUserId(), 2);// 账户积分
		if (user == null || userAmount == null || userPoint == null) {
			logger.error("售后单找不到用户或者是用户账号:{}", JSONObject.toJSONString(afterSales));
			return false;// 账户信息找不到 找不全
		}
				if(Balancefreight!=null&&Balancefreight.intValue()>0){
					//判断售后类型
					MoneyBusinessType moneyBusinessType=moneyBusinessTypeService.selectMoneyBusinessByTypeIdForCache(7);//退货返还
					Commision c=new Commision();
					c.setOrderDetailId(afterSales.getOrderDetailId());//明细ID
					c.setOrderInfoId(afterSales.getOrderInfoId());//行ID
					c.setOrderObjectId(afterSales.getOrderObjectId());//头ID
					c.setUserId(afterSales.getUserId());//用户ID
					c.setType(0);//类型 
					c.setFee(Balancefreight);//余额付
					c.setSourceId(afterSales.getId());//源ID
					c.setIsCustom(0);//是否手工
					c.setStatus(1);
					c.setResult(1);
					c.setComment("申请售后  返还 余额付运费"); //备注
					c.setBusinessTypeId(7);//类型id
					c.setBusinessTypeName(moneyBusinessType==null?"":moneyBusinessType.getTypeName());//类型名字
					int count=commisionMapper.insertSelective(c);
					if(count<=0){
						logger.error("----->添加余额事务失败,子订单号:"+afterSales.getOrderDetailId());
						return false;
					}
					//插入流水
					UserJournal balanceJournal=new UserJournal();
					balanceJournal.setUserId(c.getUserId()); 
					balanceJournal.setOrderSn(String.valueOf(afterSales.getId())); //售后单ID
					balanceJournal.setMoney(c.getFee()); 
					balanceJournal.setType("+");
					balanceJournal.setComment("售后 返还余额(运费款)");
					balanceJournal.setStatus(6);//系统返还
					balanceJournal.setBusinessTypeId(c.getBusinessTypeId());
					balanceJournal.setBusinessTypeName(c.getBusinessTypeName()); 
					balanceJournal.setIsDelete(0);
					balanceJournal.setCommisionId(c.getId().intValue());
					balanceJournal.setKeepAccountsType(KeepAccountsTypeConstants.COMMISSION_PAYMENT);
					count=userJournalMapper.insertSelective(balanceJournal);
					//生成流水成功
					if(count<=0){
						logger.error("----->添加余额流水失败,子订单号:"+afterSales.getOrderDetailId());
						return false;
					}
					// 记录用户资产的变化
					CUserMoneyChange MoneyChange = new CUserMoneyChange();
					MoneyChange.setUserId(balanceJournal.getUserId());
					MoneyChange.setOrderSn((long)balanceJournal.getId());// 源ID
					MoneyChange.setChangeAmount(balanceJournal.getMoney());
					MoneyChange.setNormalBeforAmount(userAmount.getNormalAmount());
					MoneyChange.setNormalAfterAmount(userAmount.getNormalAmount()
							+ balanceJournal.getMoney());
					MoneyChange.setSourceType(Byte.valueOf("1"));//amount
					MoneyChange.setFreeBeforAmount(userAmount.getFrozenAmount());
					MoneyChange.setFreeAfterAmount(userAmount.getFrozenAmount());
					MoneyChange.setChangeFreeAmount(0);
					moneyChangeMapper.insertSelective(MoneyChange);
					// 增加账户amount
					userMoneyMapper.increaseUserAmount(
							balanceJournal.getUserId(), 1,
							balanceJournal.getMoney());
				}
				//妆币处理
				if(Coinfreight!=null&&Coinfreight.intValue()>0){
					//判断售后类型
					MoneyBusinessType moneyBusinessType=
							moneyBusinessTypeService.selectMoneyBusinessByTypeId(16);//退货返还妆币
				   	CUserPointTransaction UserPoint=new CUserPointTransaction();
				   	UserPoint.setUserId(afterSales.getUserId());
				   	OrderInfo  info=orderInfoMapper.selectByPrimaryKey(afterSales.getOrderInfoId());
				   	UserPoint.setOrderSn(info==null?null:info.getOrderSn());
				   	UserPoint.setOrderDetailId(afterSales.getOrderDetailId());
				   	UserPoint.setOrderObjectId(afterSales.getOrderObjectId());
				   	UserPoint.setBusinessSourceId(afterSales.getId()); 
				   	UserPoint.setBusinessTypeId(moneyBusinessType.getTypeId());
				   	UserPoint.setBusinessTypeName(moneyBusinessType.getTypeName());
				   	UserPoint.setAmount(Coinfreight.longValue());
				   	UserPoint.setTransactionStatus(1); //已处理
				   	UserPoint.setIsCustom(0);//非手工
				   	UserPoint.setIsDelete(0);//没有被删除
					int count=pointTransactionMapper.insertSelective(UserPoint);
					if(count<=0){
						logger.error("----->添加积分事务失败,子订单号:"+afterSales.getOrderDetailId());
					 return false;
					}
					// 处理事务成功 插入流水
					UserPointJournal pointJournal = new UserPointJournal();
					pointJournal.setValueByPointTransaction(UserPoint);// 积分事务到积分记录表
					pointJournal.setBusinessSourceId(UserPoint.getId());//业务源单ID
					pointJournal.setKeepAccountsType(KeepAccountsTypeConstants.POINT_PAYMENT);// 财务记账类型
					count=userPointJournalMapper.insertSelective(pointJournal);
					if(count<=0){
						logger.error("----->添加积分流水失败,子订单号:"+afterSales.getOrderDetailId());
					 return false;
					}
					// 记录用户资产的变化
					CUserMoneyChange MoneyChange = new CUserMoneyChange();
					MoneyChange.setUserId(pointJournal.getUserId());
					MoneyChange.setOrderSn(pointJournal.getId());// 源ID
					MoneyChange.setChangeAmount(pointJournal.getAmount().intValue());
					MoneyChange.setNormalBeforAmount(userPoint.getNormalAmount());
					MoneyChange.setNormalAfterAmount(userPoint.getNormalAmount()
							+pointJournal.getAmount().intValue());
					MoneyChange.setSourceType(Byte.valueOf("2"));// 积分
					MoneyChange.setFreeBeforAmount(userPoint.getFrozenAmount());
					MoneyChange.setFreeAfterAmount(userPoint.getFrozenAmount());
					MoneyChange.setChangeFreeAmount(0);
					moneyChangeMapper.insertSelective(MoneyChange);
					// 增加账户妆币
					userMoneyMapper.increaseUserAmount(
							pointJournal.getUserId(), 2,
							pointJournal.getAmount());
				}
				//都处理完了 可以处理售后单了
				int count=afterSalesMapper.updateAfterSalesFreightByID( 
				afterSales.getId(), Coinfreight==null?0:Coinfreight, Balancefreight==null?0:Balancefreight);
				if(count<=0){
					logger.error("----->保存售后单的保存余额妆币 运费退账。失败,子订单号:"+afterSales.getOrderDetailId());
				 return false;
				}
				return true;
	}

	
	@Override
	public ResponseEntity<?> storeRefusedAfterSales(long afterSalesId,String storeRefuseReason,String storeRefuseReason1) throws Exception {
		// TODO Auto-generated method stub
		AfterSales afterSale = afterSalesMapper.selectAfterSalesByPrimyKey(afterSalesId);
		
		if (afterSale.getType() == 1 && afterSale.getStatus() == 4) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21208), HttpStatus.OK);
		}
		
		if (afterSale.getType() == 2 && afterSale.getStatus() == 4) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C21209), HttpStatus.OK);
		}
		
		int timeMillin = 0;
		if (afterSale.getType() == 1) {
			timeMillin = (int) ((new Date().getTime() - (DateUtil.parse(afterSale.getCreateTime()).getTime()))/1000/60);
			// 修改售后订单的状态为拒绝
			int updateAfterStatus = afterSalesMapper.updateAfterSalesStoreRefusedReason(afterSale.getId(),4,storeRefuseReason);
			if(updateAfterStatus <= 0){
				throw new Exception();
			}
			int delOrderInfoRefundStatus = orderDetailMapper.updateOrderDetailRefundToOpen(afterSale.getOrderDetailId());
			if(delOrderInfoRefundStatus <= 0){
				throw new Exception();
			}
		}else{
			timeMillin = (int) ((new Date().getTime() - (DateUtil.parse(afterSale.getUpdateTime()).getTime()))/1000/60);
			// 修改售后订单的状态为拒绝
			int updateAfterStatus = afterSalesMapper.updateAfterSalesStoreRefusedReason1(afterSale.getId(),4,storeRefuseReason1);
			if(updateAfterStatus <= 0){
				throw new Exception();
			}
			int delOrderInfoRefundStatus = orderDetailMapper.updateOrderDetailRefundToOpen(afterSale.getOrderDetailId());
			if(delOrderInfoRefundStatus <= 0){
				throw new Exception();
			}
		}
		
		// 子订单层级
		List<OrderDetail> detailList = orderDetailMapper.selectOrderDetailByOrderInfoIdC(afterSale.getOrderInfoId());
		boolean infoFlag = true;
		for (OrderDetail detail : detailList) {
			if(detail.getStatus() == 4 && detail.getRefund()==1){
				infoFlag = false;
			}
			if(detail.getStatus() == 3 && detail.getRefund()==1){
				infoFlag = false;
			}
			if(detail.getStatus() == 2 && detail.getRefund()==1){
				infoFlag = false;
			}
		}
		// 取消子订单的售后状态
		if (infoFlag) {
			int updateInfoFlag = orderInfoMapper.updateOrderInfoRefundByFlag(afterSale.getOrderInfoId());
			if (updateInfoFlag <= 0) {
				throw new Exception();
			}
		}
		
		// 父订单层级
		boolean objFlag = true;
		List<OrderInfo> orderInfoList = orderInfoMapper.selectOrderInfoByOrderObjectIdC(afterSale.getOrderObjectId());
		for (OrderInfo info : orderInfoList) {
			if (info.getRefund() == 1 && info.getStatus() == 4) {
				objFlag = false;
			}
			if (info.getRefund() == 1 && info.getStatus() == 3) {
				objFlag = false;
			}
			if (info.getRefund() == 1 && info.getStatus() == 2) {
				objFlag = false;
			}
		}
		if(objFlag){
			int updateObjFlagStatus = orderObjectMapper.updateOrderObjectRefundByFlag(afterSale.getOrderObjectId());
			if (updateObjFlagStatus <= 0) {
				throw new Exception();
			}
		}
		
		// 放入分佣时间
		int updateRefundTime = orderObjectMapper.updateRefundTimeById(afterSale.getOrderObjectId(), timeMillin);
		if (updateRefundTime <= 0) {
			throw new Exception();
		}
		
		if (afterSale.getHistory() == 1) {
			/**
			 * 绑定解冻
			 */
			OrderDetail orderDetail = orderDetailMapper.selectByPrimaryKey(afterSale.getOrderDetailId());
			freezeOrder(afterSale.getProductBn(), afterSale.getOrderInfoSn(), afterSale.getCustomerServiceNumber(), orderDetail, 1,0);
		}
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	@Override
	public long getFatherOrdersOfTotalPrice(long orderObjectId) {
		// TODO Auto-generated method stub
		return afterSalesMapper.selectFatherOrdersOfTotalPrice(orderObjectId);
	}

	@Override
	public long getRefundSuccessMoney(long orderObjectId) {
		// TODO Auto-generated method stub
		return afterSalesMapper.selectRefundSuccessMoney(orderObjectId);
	}

	/**
	 * 校妆OMS调用
	 * 退货入库通知
	 */
	@Override
	public ResponseEntity<?> afterSalesNotice(String appKey, String data, String sign) {
		// TODO Auto-generated method stub
		AppSecret appSecret = appSecretMapper.selectAppSecret(appKey);
		if (appSecret == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20150), HttpStatus.OK);
		}
		StringBuffer sg = new StringBuffer();
		// 拼接data+sign
		sg.append(data).append(appSecret.getSecret());
		// MD5加密
		String md = stringMD5(sg.toString());
		// sign不匹配返回结果
		if (!md.equals(sign)) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20151), HttpStatus.OK);
		}
		// base64解密
		String result = Base64Util.decode(data);
		
		logger.info("------>Back:" + result);
		
		String returnSn = JSONObject.parseObject(result).get("orderSn").toString();
		
		AfterSales afterSale = afterSalesMapper.selectAfterSalesByReturnSn(returnSn);
		
		if (afterSale == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20806), HttpStatus.OK);
		}
		
		afterSalesMapper.updateSendBackById(afterSale.getId(), 2);
		
		// 售后扩展用
		// String defectiveGoods = JSONObject.parseObject(result).get("defective_goods").toString();
		// defective_goods
		// afterSalesMapper.updateAfterSalesGoodsInformation(afterSale.getId(),defectiveGoods);
		
		XZAfterSalesLog logModel = new XZAfterSalesLog();
		logModel.setOrderInfoSn(afterSale.getOrderInfoSn());
		logModel.setResult("OMS回调成功，订单已成功入库");
		logModel.setAfterSn(afterSale.getCustomerServiceNumber());
		logModel.setSteps(6);
		logModel.setRemark("OMS已确认入库，可以退款");
		xZAfterSalesLogMapper.insertIntoLogs(logModel);
		
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	/**
	 * 校妆OMS调用
	 * 拒单包裹通知
	 *
	 * @author gaoweiqi
	 * @date 2017年11月27日 12:44:05
	 **/
	@Override
	public ResponseEntity<?> afterSalesRejection(String appKey, String data, String sign) {
		AppSecret appSecret = appSecretMapper.selectAppSecret(appKey);
		if (appSecret == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20150), HttpStatus.OK);
		}
		StringBuffer sg = new StringBuffer();
		// 拼接data+sign
		sg.append(data).append(appSecret.getSecret());
		// MD5加密
		String md = stringMD5(sg.toString());
		// sign不匹配返回结果
		if (!md.equals(sign)) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20151), HttpStatus.OK);
		}
		// base64解密
		String result = Base64Util.decode(data);
		String returnSn = JSONObject.parseObject(result).get("return_order_id").toString();
		String orderSn = JSONObject.parseObject(result).get("order_sn").toString();
		List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
		OrderInfo orderInfo = new OrderInfo();
		if (orderSn.substring(0, 1).equals("P")) {
			OrderObject orderObject = orderObjectMapper.selectByOrderSn(orderSn);
			if (orderObject == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}
			orderDetails = orderDetailMapper.selectOrderDetilByOrderObjectId(orderObject.getId());
		} else {
			orderInfo = orderInfoMapper.selectOrderInfoEntityByOrderSn(orderSn);
			if (orderInfo == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20802), HttpStatus.OK);
			}
			orderDetails = orderDetailMapper.selectOrderDetailByOrderInfoIdC(orderInfo.getId());
		}

		//开店商品限制售后
		if (orderDetails != null && orderDetails.size() > 0) {
			BaseRestrictions baseRestrictions =
					baseRestrictionsService.getBaseRestrictionsForCache("open_store_limit_after_sale");
			OrderObject orderObject = orderObjectMapper.selectOrderObjectById(orderDetails.get(0).getOrderObjectId());
			//限制开店单不允许售后
			if (orderObject.getOpenStore() == 1 && baseRestrictions != null &&
					DateUtils.compare_date_HHmmss(DateUtil.getNow(), baseRestrictions.getName()) > 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C80001), HttpStatus.OK);
			}
		}

		AfterSales saveModel = new AfterSales();
		for (OrderDetail orderDetail : orderDetails) {
			try {
				AfterSales afterSale = afterSalesMapper.selectAfterSalesByOrderDetailId(orderDetail.getId());
				if (afterSale != null) continue;
				Product product = productMapper.selectProductByIdNoStatus(orderDetail.getProductId());
				String autoSn = "A" + OrderUtil.getOrderSn();
				saveModel.setUserId(orderDetail.getUserId());
				saveModel.setOrderDetailId(orderDetail.getId());
				saveModel.setOrderObjectId(orderDetail.getOrderObjectId());
				saveModel.setOrderInfoId(orderDetail.getOrderId());
				saveModel.setIsRefund(2);
				saveModel.setCustomerServiceNumber(autoSn);
				saveModel.setUserRefundReason("拒签订单，系统自动售后。");
				saveModel.setUserFirstReason("");
				saveModel.setImgProof1("");
				saveModel.setImgProof2("");
				saveModel.setImgProof3("");
				saveModel.setRefundCashMoney(orderDetail.getCashCoin());//积分
				saveModel.setStoreId(orderDetail.getStoreId().longValue());
				saveModel.setRefundMoney(orderDetail.getTotalFee().longValue());//实际退款
				saveModel.setRefundBalancePaid(orderDetail.getBalancePaid()); //余额付
				saveModel.setType(1);
				saveModel.setQuantity(orderDetail.getQuantity());
				saveModel.setOrderInfoSn(orderInfo.getOrderSn());
				saveModel.setProductBn(product.getProductBn());
				saveModel.setProductId(product.getId());
				saveModel.setStatus(1);
				saveModel.setSendBack(2);
				saveModel.setReturnOrderId(returnSn);
				saveThis(saveModel, true);
			} catch (Exception e) {
				// TODO: handle exception
				logger.info("捕获未知异常！");
			}
		}
		afterSalesMapper.updateAfterSalesReturnOrderIdByOrderInfoSn(orderInfo.getOrderSn(), returnSn);
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}

	@Override
	public void omsReturn(String orderSn) {
		// TODO Auto-generated method stub
		// AfterSales afterSale = afterSalesMapper.selectAfterSalesByCustomerServiceNumber(orderSn);
		
		List<AfterSales> afterSalesList = afterSalesMapper.selectTempSQL();
		for (AfterSales afterSale : afterSalesList) {
			OrderDetail orderDetail = orderDetailMapper.selectByPrimaryKey(afterSale.getOrderDetailId());
			/*if (afterSale.getReturnOrderId() != "") {
				addRefundOrder(afterSale.getProductBn(), afterSale.getOrderInfoSn(),
						afterSale.getCustomerServiceNumber(), orderDetail, afterSale.getReturnOrderId(),
						afterSale.getCreateTime());
			} else {
				freezeOrder(afterSale.getProductBn(), afterSale.getOrderInfoSn(), afterSale.getCustomerServiceNumber(), orderDetail,0);
			}*/
			
			if (afterSale.getReturnOrderId() != null && !"".equals(afterSale.getReturnOrderId())) {
				addRefundOrder(afterSale.getProductBn(), afterSale.getOrderInfoSn(),
						afterSale.getCustomerServiceNumber(), orderDetail, afterSale.getReturnOrderId(),
						afterSale.getCreateTime());
			} else {
				freezeOrder(afterSale.getProductBn(), afterSale.getOrderInfoSn(), afterSale.getCustomerServiceNumber(), orderDetail,0,0);
			}
			
		}
	}

	@Override
	public Map<String, Object> validationAfterSales(AfterSales afterSalesTemp) {
		Map<String, Object> map=new HashMap<String, Object>();
		OrderDetail OrderDetail=
				orderDetailMapper.selectByPrimaryKey(afterSalesTemp.getOrderDetailId());
		OrderInfo orderInfo=
				orderInfoMapper.selectByPrimaryKey(afterSalesTemp.getOrderInfoId());
		if(OrderDetail==null){
			map.put("1",afterSalesTemp.getCustomerServiceNumber());
			map.put("2", "未找到该售后单的订单行");
			return map;
		}
		if(afterSalesTemp.getRefundMoney().intValue()!=OrderDetail.getTotalFee().intValue()
				||afterSalesTemp.getRefundCashMoney()!=OrderDetail.getCashCoin().intValue()
				||afterSalesTemp.getRefundBalancePaid()!=OrderDetail.getBalancePaid().intValue()){
			map.put("1",afterSalesTemp.getCustomerServiceNumber());
			map.put("2", "该售后单记录的实际退款金额与明细订单不符");
			return map;
		}
		if((afterSalesTemp.getStatus()==2&&StringUtils.isNotBlank(afterSalesTemp.getRefundId()))
				||(afterSalesTemp.getStatus()==3&&StringUtils.isBlank(afterSalesTemp.getRefundId()))){
			map.put("1", afterSalesTemp.getCustomerServiceNumber());
			map.put("2", "该售后单的售后状态异常");
			return map;
		}
		//验证实际退款金额
		if(afterSalesTemp.getStatus()==3){
			//售后单相关的 佣金事务 流水  是否正常
			 List<Commision> CommisionList=commisionMapper.selectdoneBusinessByDetailID(afterSalesTemp.getOrderDetailId());
			 int sumFee=0;
			 for(Commision commision:CommisionList){
				 sumFee+=commision.getFee().intValue();
			 }
			 if(sumFee!=0){
				 map.put("1",afterSalesTemp.getCustomerServiceNumber());
				 map.put("2", "该售后单的余额事务异常 异常金额:"+sumFee);
					return map;
			 }
			for(Commision  commision:CommisionList){
					List<UserJournal> UserJournalList=
						userJournalMapper.selectJournalByCommisionId(commision.getId().intValue());
				   if(UserJournalList!=null&&UserJournalList.size()>1){
					   map.put("1",afterSalesTemp.getCustomerServiceNumber());
					   map.put("2", "售后单余额返还流水重复");
						return map;
				   }
				   if(UserJournalList==null||UserJournalList.size()==0){
					   map.put("1", afterSalesTemp.getCustomerServiceNumber());
					   map.put("2", "未找到该售后单余额事务的流水");
						return map;
				   }
				   if(UserJournalList.get(0).getBusinessTypeId()!=commision.getBusinessTypeId().intValue()){
					   map.put("1", afterSalesTemp.getCustomerServiceNumber());
					   map.put("2", "售后单余额事务和订单的账务类型不一致");
						return map;
				   }
				}
			//售后单相关的妆币 事务 流水是否正常
			 List<CUserPointTransaction> PointTransactionList=cUserPointTransactionMapper.selectdoneBusinessByDetailID(afterSalesTemp.getOrderDetailId());
			 sumFee=0;
			 for(CUserPointTransaction pointTransaction:PointTransactionList){
				 sumFee+=pointTransaction.getAmount().intValue();
			 }
			 if(sumFee!=0){
				 map.put("1",afterSalesTemp.getCustomerServiceNumber());
				 map.put("2", "该售后单的妆币事务异常");
					return map;
			 }
				for(CUserPointTransaction  CUserPointTransaction:PointTransactionList){
					List<UserPointJournal> UserPointJournalList=
							userPointJournalMapper.selectBySourceIDBusinessType(CUserPointTransaction.getId(), CUserPointTransaction.getBusinessTypeId());
					if(UserPointJournalList!=null&&UserPointJournalList.size()>1){
						   map.put("1",afterSalesTemp.getCustomerServiceNumber());
						   map.put("2", "售后单订单妆币流水重复");
							return map;
					   }
					   if(UserPointJournalList==null||UserPointJournalList.size()==0){
						   map.put("1", afterSalesTemp.getCustomerServiceNumber());
						   map.put("2", "未找到该订单妆币的流水");
							return map;
					   }
				}
			 //验证运费退款金额
			 if(afterSalesTemp.getRefundBalanceFreight()!=null||
					 afterSalesTemp.getRefundCashFreight()!=null||
					 afterSalesTemp.getRefundFreight()!=null){
				 long i=(afterSalesTemp.getRefundBalanceFreight()!=null?afterSalesTemp.getRefundBalanceFreight().longValue():0)+
				 (afterSalesTemp.getRefundCashFreight()!=null?afterSalesTemp.getRefundCashFreight().longValue():0)+
				 (afterSalesTemp.getRefundFreight()!=null?afterSalesTemp.getRefundFreight().longValue():0);
				 long j=orderInfo.getFreight()!=null?orderInfo.getFreight().longValue():0;
				 if(i!=j){//运费不一致
					 map.put("1", afterSalesTemp.getCustomerServiceNumber());
					 map.put("2", "该售后单的运费退款和info订单上不一致");
						return map;
				 }
			 }
			if(afterSalesTemp.getRefundBalancePaid()>0||afterSalesTemp.getRefundBalanceFreight()!=null){//使用了余额付款
				ParamsCommisionVo paramsCommisionVo = new ParamsCommisionVo();
				paramsCommisionVo.setStatus(1);
				paramsCommisionVo.setResult(1);
				paramsCommisionVo.getBusinessTypeSet().add(7);//退货返还
				paramsCommisionVo.setSourceId(afterSalesTemp.getId());
				long Refund_balance_freight=
				afterSalesTemp.getRefundBalanceFreight()!=null?afterSalesTemp.getRefundBalanceFreight().longValue():0;
				List<Commision> commisionList = commissionService.queryAll(paramsCommisionVo);//查找所有的处理过的余额付
				long sum=0;
				for(Commision c:commisionList){
					sum+=c.getFee().longValue();					
				}
			   if(sum!=Refund_balance_freight+afterSalesTemp.getRefundBalancePaid()){
				   map.put("1",afterSalesTemp.getCustomerServiceNumber());
				   map.put("2", "该售后单的余额事务异常");
					return map;
			   }
				for(Commision  commision:commisionList){
					List<UserJournal> UserJournalList=
						userJournalMapper.selectJournalByCommisionId(commision.getId().intValue());
				   if(UserJournalList!=null&&UserJournalList.size()>1){
					   map.put("1",afterSalesTemp.getCustomerServiceNumber());
					   map.put("2", "售后单余额返还流水重复");
						return map;
				   }
				   if(UserJournalList==null||UserJournalList.size()==0){
					   map.put("1",afterSalesTemp.getCustomerServiceNumber());
					   map.put("2", "未找到该售后单余额事务的流水");
						return map;
				   }
				   if(UserJournalList.get(0).getBusinessTypeId()!=commision.getBusinessTypeId().intValue()){
					   map.put("1",afterSalesTemp.getCustomerServiceNumber());
					   map.put("2", "售后单余额事务和订单的账务类型不一致");
						return map;
				   }
				}	
			}
			if(afterSalesTemp.getRefundCashMoney()>0||afterSalesTemp.getRefundCashFreight()!=null){//妆币返还
				//积分事务
				ParamsUserXzbTransactionVo params_user_xzb_transaction=new ParamsUserXzbTransactionVo();
				params_user_xzb_transaction.setTransactionStatus(1);
				params_user_xzb_transaction.getBusinessTypeSet().add(16);//退货返还妆币
				params_user_xzb_transaction.setBusinessSourceId(afterSalesTemp.getId());
				  List<CUserPointTransaction> CUserPointTransactionList=
							 cUserPointTransactionService.queryAll(params_user_xzb_transaction);
				 long Refund_cash_freight=
						afterSalesTemp.getRefundCashFreight()!=null?afterSalesTemp.getRefundCashFreight().longValue():0;
				long sumFese=0L;
						for(CUserPointTransaction c:CUserPointTransactionList){
							sumFese+=c.getAmount().longValue(); 
				}		
						if(sumFese!=afterSalesTemp.getRefundCashMoney()+Refund_cash_freight){
							map.put(afterSalesTemp.getCustomerServiceNumber(), "售后单妆币事务和售后单信息不符");
							return map;
						}
					//验证妆币产生的流水
					for(CUserPointTransaction  CUserPointTransaction:CUserPointTransactionList){
						List<UserPointJournal> UserPointJournalList=
								userPointJournalMapper.selectBySourceIDBusinessType(CUserPointTransaction.getId(), CUserPointTransaction.getBusinessTypeId());
						if(UserPointJournalList!=null&&UserPointJournalList.size()>1){
							map.put("1",afterSalesTemp.getCustomerServiceNumber());
							map.put("2", "订单妆币流水重复或者为空");
							return map;
						}
					}
			}
		}
		return null;
	}
	private WeChat getWeChat(int payType) {
		WeChat theWeChat=null;
		if(payType==PayTypeEnum.T1.getCode())
		{
			for (WeChat weChat : weChatList) {
				if(weChat instanceof WeChat0Impl)
				{
					theWeChat= weChat;
				}
			}
		}
		else if(payType==PayTypeEnum.T3.getCode())
		{
			for (WeChat weChat : weChatList) {
				if(weChat instanceof WeChatImpl)
				{
					theWeChat= weChat;
				}
			}
		}
		else
		{
			theWeChat=weChatList.get(0);
		}
		return theWeChat;
	}
}
